#!/usr/bin/perl -w
# File: send_commands.pl
# Usage: send_comands.pl
# Author: Tao Zhang

use strict;
use warnings;
use POSIX qw(:signal_h);
use Proc::Daemon;
use IO::Socket;
use Digest::MD5;
use MLUtils::Logger qw(mllogerr);

$| = 1;
my $file_name = "zt";
my $size = -s "/home/t0612z/Downloads/zt";
my $command = "";
my $timeout = 10;

# -------------------subroutines----------------------------
sub wait_for_feedback($) {
    my $server = shift;

    my $input = undef;
    
    eval {
        local $SIG{'ALRM'} = sub { die "Timed out" };
        alarm($timeout);
        $input = <$server>;
        alarm(0);
    };
    
    if ($@ =~ /Timed out/) {
        print STDERR "Waitting for control string timed Out.\n";
        $server->close();
        exit -1;
    }
    
    if ($input) {
        return $input;
    } else {
        print STDERR "Failed to read from client.\n";
        $server->close();
        exit -1;
    }
}

# -----------------------main-------------------------------
my $server = IO::Socket::INET->new(
    PeerAddr => '10.10.0.203',
    PeerPort => 8000,
    Proto    => 'tcp'
) or die "Can't create client socket: $!";

$server->autoflush(1);

print $server "MLTRAN:COMMAND\n";
print "CMD:>>";

while ( my $cmd = <STDIN>) {
    $| = 1;
    if ( ! $server->connected() ) {
        print STDERR "Server closed.\n";
        exit 0;
    }
    
    if ($cmd =~ /quit/i) {
        print $server "quit\n";
        select(undef,undef,undef, 0.25);
        $server->close();
        last;
    }
    print $server $cmd;

    #print $server "$command";
    while (my $recv = wait_for_feedback($server)) {
        if ($recv =~ /MLTRAN:EOC/i) {
            last;
        }
        chomp($recv);
        print $recv,"\n";
    }  
    print "CMD:>>";
}
exit 0;
